package org.alwayssuper.protocol.commons.transform.realtimev2016;

import org.alwayssuper.protostar.annotation.Field;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;

import java.util.List;

/**
 * 2016版报警数据格式 (0x07)
 * 参考AICoding报文规则文档
 * @author alwaysSuper
 */
@ToString
@Data
@Accessors(chain = true)
public class AlarmData {
    @Field(length = 1, desc = "最高报警等级:0:无故障;1:1级故障;2:2级故障;3:3级故障")
    private int maxAlarmLevel;
    
    @Field(length = 4, desc = "通用报警标志:32bit报警标志位,见GB/T32960.3-2016表18")
    private int generalAlarmFlag;
    
    // 通用报警标志位定义常量 - 基于GB/T32960.3-2016表18
    public static final int TEMP_DIFF_ALARM = 0;                    // 位0: 温度差异报警
    public static final int BATTERY_HIGH_TEMP_ALARM = 1;            // 位1: 电池高温报警
    public static final int BATTERY_OVERVOLTAGE_ALARM = 2;          // 位2: 车载储能装置类型过压报警
    public static final int BATTERY_UNDERVOLTAGE_ALARM = 3;         // 位3: 车载储能装置类型欠压报警
    public static final int SOC_LOW_ALARM = 4;                      // 位4: SOC低报警
    public static final int CELL_OVERVOLTAGE_ALARM = 5;             // 位5: 单体电池过压报警
    public static final int CELL_UNDERVOLTAGE_ALARM = 6;            // 位6: 单体电池欠压报警
    public static final int SOC_HIGH_ALARM = 7;                     // 位7: SOC过高报警
    public static final int SOC_JUMP_ALARM = 8;                     // 位8: SOC跳变报警
    public static final int ENERGY_STORAGE_MISMATCH_ALARM = 9;      // 位9: 可充电储能系统不匹配报警
    public static final int CELL_CONSISTENCY_ALARM = 10;            // 位10: 电池单体一致性差报警
    public static final int INSULATION_ALARM = 11;                  // 位11: 绝缘报警
    public static final int DCDC_TEMP_ALARM = 12;                   // 位12: DC-DC温度报警
    public static final int BRAKE_SYSTEM_ALARM = 13;                // 位13: 制动系统报警
    public static final int DCDC_STATUS_ALARM = 14;                 // 位14: DC-DC状态报警
    public static final int MOTOR_CONTROLLER_TEMP_ALARM = 15;       // 位15: 驱动电机控制器温度报警
    public static final int HIGH_VOLTAGE_INTERLOCK_ALARM = 16;      // 位16: 高压互锁状态报警
    public static final int MOTOR_TEMP_ALARM = 17;                  // 位17: 驱动电机温度报警
    public static final int BATTERY_OVERCHARGE_ALARM = 18;          // 位18: 车载储能装置类型过充
    // 位19~31: 预留
    
    // 可充电储能装置故障总数N1:0~252(由batteryAlarmCodes的totalUnit获取)
    private int batteryAlarmCount;
    
    @Field(totalUnit = 1, desc = "可充电储能装置故障代码列表")
    private int[] batteryAlarmCodes;
    
    // 驱动电机故障总数N2:0~252(由motorAlarmCodes的totalUnit获取)
    private int motorAlarmCount;
    
    @Field(totalUnit = 1, desc = "驱动电机故障代码列表")
    private int[] motorAlarmCodes;
    
    // 发动机故障总数N3:0~252(由engineAlarmCodes的totalUnit获取)
    private int engineAlarmCount;
    
    @Field(totalUnit = 1, desc = "发动机故障代码列表")
    private int[] engineAlarmCodes;
    
    // 其他故障总数N4:0~252(由otherAlarmCodes的totalUnit获取)
    private int otherAlarmCount;
    
    @Field(totalUnit = 1, desc = "其他故障代码列表")
    private int[] otherAlarmCodes;
    
    // 通过各个故障代码列表长度返回对应的故障总数
    public int getBatteryAlarmCount() {
        return batteryAlarmCodes == null ? 0 : batteryAlarmCodes.length;
    }
    
    public int getMotorAlarmCount() {
        return motorAlarmCodes == null ? 0 : motorAlarmCodes.length;
    }
    
    public int getEngineAlarmCount() {
        return engineAlarmCodes == null ? 0 : engineAlarmCodes.length;
    }
    
    public int getOtherAlarmCount() {
        return otherAlarmCodes == null ? 0 : otherAlarmCodes.length;
    }
    
    /**
     * 检查指定位的报警状态
     * @param bitPosition 位位置 (0-31)
     * @return true: 报警, false: 正常
     */
    public boolean isAlarmBitSet(int bitPosition) {
        if (bitPosition < 0 || bitPosition > 31) {
            throw new IllegalArgumentException("位位置必须在0-31范围内");
        }
        return (generalAlarmFlag & (1 << bitPosition)) != 0;
    }

    /**
     * 设置指定位的报警状态
     * @param bitPosition 位位置 (0-31)
     * @param alarm true: 设置报警, false: 清除报警
     */
    public void setAlarmBit(int bitPosition, boolean alarm) {
        if (bitPosition < 0 || bitPosition > 31) {
            throw new IllegalArgumentException("位位置必须在0-31范围内");
        }
        if (alarm) {
            generalAlarmFlag |= (1 << bitPosition);
        } else {
            generalAlarmFlag &= ~(1 << bitPosition);
        }
    }

    // 便捷方法：检查具体报警类型
    public boolean isTempDiffAlarm() { return isAlarmBitSet(TEMP_DIFF_ALARM); }
    public boolean isBatteryHighTempAlarm() { return isAlarmBitSet(BATTERY_HIGH_TEMP_ALARM); }
    public boolean isBatteryOvervoltageAlarm() { return isAlarmBitSet(BATTERY_OVERVOLTAGE_ALARM); }
    public boolean isBatteryUndervoltageAlarm() { return isAlarmBitSet(BATTERY_UNDERVOLTAGE_ALARM); }
    public boolean isSocLowAlarm() { return isAlarmBitSet(SOC_LOW_ALARM); }
    public boolean isCellOvervoltageAlarm() { return isAlarmBitSet(CELL_OVERVOLTAGE_ALARM); }
    public boolean isCellUndervoltageAlarm() { return isAlarmBitSet(CELL_UNDERVOLTAGE_ALARM); }
    public boolean isSocHighAlarm() { return isAlarmBitSet(SOC_HIGH_ALARM); }
    public boolean isSocJumpAlarm() { return isAlarmBitSet(SOC_JUMP_ALARM); }
    public boolean isEnergyStorageMismatchAlarm() { return isAlarmBitSet(ENERGY_STORAGE_MISMATCH_ALARM); }
    public boolean isCellConsistencyAlarm() { return isAlarmBitSet(CELL_CONSISTENCY_ALARM); }
    public boolean isInsulationAlarm() { return isAlarmBitSet(INSULATION_ALARM); }
    public boolean isDcdcTempAlarm() { return isAlarmBitSet(DCDC_TEMP_ALARM); }
    public boolean isBrakeSystemAlarm() { return isAlarmBitSet(BRAKE_SYSTEM_ALARM); }
    public boolean isDcdcStatusAlarm() { return isAlarmBitSet(DCDC_STATUS_ALARM); }
    public boolean isMotorControllerTempAlarm() { return isAlarmBitSet(MOTOR_CONTROLLER_TEMP_ALARM); }
    public boolean isHighVoltageInterlockAlarm() { return isAlarmBitSet(HIGH_VOLTAGE_INTERLOCK_ALARM); }
    public boolean isMotorTempAlarm() { return isAlarmBitSet(MOTOR_TEMP_ALARM); }
    public boolean isBatteryOverchargeAlarm() { return isAlarmBitSet(BATTERY_OVERCHARGE_ALARM); }

    // 便捷方法：设置具体报警类型
    public void setTempDiffAlarm(boolean alarm) { setAlarmBit(TEMP_DIFF_ALARM, alarm); }
    public void setBatteryHighTempAlarm(boolean alarm) { setAlarmBit(BATTERY_HIGH_TEMP_ALARM, alarm); }
    public void setBatteryOvervoltageAlarm(boolean alarm) { setAlarmBit(BATTERY_OVERVOLTAGE_ALARM, alarm); }
    public void setBatteryUndervoltageAlarm(boolean alarm) { setAlarmBit(BATTERY_UNDERVOLTAGE_ALARM, alarm); }
    public void setSocLowAlarm(boolean alarm) { setAlarmBit(SOC_LOW_ALARM, alarm); }
    public void setCellOvervoltageAlarm(boolean alarm) { setAlarmBit(CELL_OVERVOLTAGE_ALARM, alarm); }
    public void setCellUndervoltageAlarm(boolean alarm) { setAlarmBit(CELL_UNDERVOLTAGE_ALARM, alarm); }
    public void setSocHighAlarm(boolean alarm) { setAlarmBit(SOC_HIGH_ALARM, alarm); }
    public void setSocJumpAlarm(boolean alarm) { setAlarmBit(SOC_JUMP_ALARM, alarm); }
    public void setEnergyStorageMismatchAlarm(boolean alarm) { setAlarmBit(ENERGY_STORAGE_MISMATCH_ALARM, alarm); }
    public void setCellConsistencyAlarm(boolean alarm) { setAlarmBit(CELL_CONSISTENCY_ALARM, alarm); }
    public void setInsulationAlarm(boolean alarm) { setAlarmBit(INSULATION_ALARM, alarm); }
    public void setDcdcTempAlarm(boolean alarm) { setAlarmBit(DCDC_TEMP_ALARM, alarm); }
    public void setBrakeSystemAlarm(boolean alarm) { setAlarmBit(BRAKE_SYSTEM_ALARM, alarm); }
    public void setDcdcStatusAlarm(boolean alarm) { setAlarmBit(DCDC_STATUS_ALARM, alarm); }
    public void setMotorControllerTempAlarm(boolean alarm) { setAlarmBit(MOTOR_CONTROLLER_TEMP_ALARM, alarm); }
    public void setHighVoltageInterlockAlarm(boolean alarm) { setAlarmBit(HIGH_VOLTAGE_INTERLOCK_ALARM, alarm); }
    public void setMotorTempAlarm(boolean alarm) { setAlarmBit(MOTOR_TEMP_ALARM, alarm); }
    public void setBatteryOverchargeAlarm(boolean alarm) { setAlarmBit(BATTERY_OVERCHARGE_ALARM, alarm); }

    /**
     * 清除所有报警标志
     */
    public void clearAllAlarms() {
        generalAlarmFlag = 0;
    }

    /**
     * 检查是否有任何报警
     * @return true: 有报警, false: 无报警
     */
    public boolean hasAnyAlarm() {
        return generalAlarmFlag != 0;
    }

    /**
     * 获取报警标志的二进制字符串表示
     * @return 32位二进制字符串
     */
    public String getAlarmBinaryString() {
        return String.format("%32s", Integer.toBinaryString(generalAlarmFlag)).replace(' ', '0');
    }

    /**
     * 获取报警标志的十六进制字符串表示
     * @return 十六进制字符串
     */
    public String getAlarmHexString() {
        return String.format("0x%08X", generalAlarmFlag);
    }

    /**
     * 获取当前所有激活报警的描述
     * @return 报警描述列表
     */
    public java.util.List<String> getActiveAlarmDescriptions() {
        java.util.List<String> alarms = new java.util.ArrayList<>();
        if (isTempDiffAlarm()) alarms.add("温度差异报警");
        if (isBatteryHighTempAlarm()) alarms.add("电池高温报警");
        if (isBatteryOvervoltageAlarm()) alarms.add("车载储能装置类型过压报警");
        if (isBatteryUndervoltageAlarm()) alarms.add("车载储能装置类型欠压报警");
        if (isSocLowAlarm()) alarms.add("SOC低报警");
        if (isCellOvervoltageAlarm()) alarms.add("单体电池过压报警");
        if (isCellUndervoltageAlarm()) alarms.add("单体电池欠压报警");
        if (isSocHighAlarm()) alarms.add("SOC过高报警");
        if (isSocJumpAlarm()) alarms.add("SOC跳变报警");
        if (isEnergyStorageMismatchAlarm()) alarms.add("可充电储能系统不匹配报警");
        if (isCellConsistencyAlarm()) alarms.add("电池单体一致性差报警");
        if (isInsulationAlarm()) alarms.add("绝缘报警");
        if (isDcdcTempAlarm()) alarms.add("DC-DC温度报警");
        if (isBrakeSystemAlarm()) alarms.add("制动系统报警");
        if (isDcdcStatusAlarm()) alarms.add("DC-DC状态报警");
        if (isMotorControllerTempAlarm()) alarms.add("驱动电机控制器温度报警");
        if (isHighVoltageInterlockAlarm()) alarms.add("高压互锁状态报警");
        if (isMotorTempAlarm()) alarms.add("驱动电机温度报警");
        if (isBatteryOverchargeAlarm()) alarms.add("车载储能装置类型过充");
        return alarms;
    }
    
    // =========================== 报警等级与状态值转换方法 ===========================
    
    /**
     * 检查最高报警等级是否有效
     * @return true: 有效, false: 无效
     */
    public boolean isMaxAlarmLevelValid() {
        return maxAlarmLevel >= 0 && maxAlarmLevel <= 3;
    }
    
    /**
     * 获取最高报警等级的描述
     * @return 报警等级描述
     */
    public String getMaxAlarmLevelDescription() {
        switch (maxAlarmLevel) {
            case 0: return "无故障";
            case 1: return "1级故障";
            case 2: return "2级故障";
            case 3: return "3级故障";
            default: return "未知故障等级";
        }
    }
    
    /**
     * 检查通用报警标志是否异常
     * 0xFFFFFFFE: 异常, 0xFFFFFFFF: 无效
     */
    public boolean isGeneralAlarmFlagAbnormal() {
        return generalAlarmFlag == 0xFFFFFFFE;
    }
    
    /**
     * 检查通用报警标志是否无效
     * 0xFFFFFFFE: 异常, 0xFFFFFFFF: 无效
     */
    public boolean isGeneralAlarmFlagInvalid() {
        return generalAlarmFlag == 0xFFFFFFFF;
    }
    
    /**
     * 获取所有报警代码的总数
     * @return 所有类型报警代码的总数
     */
    public int getTotalAlarmCodeCount() {
        return getBatteryAlarmCount() + getMotorAlarmCount() + 
               getEngineAlarmCount() + getOtherAlarmCount();
    }
    
    /**
     * 检查是否存在任何类型的报警代码
     * @return true: 存在报警代码, false: 无报警代码
     */
    public boolean hasAnyAlarmCode() {
        return getTotalAlarmCodeCount() > 0;
    }
    
    /**
     * 获取所有报警代码（合并所有类型）
     * @return 所有报警代码的列表
     */
//    public java.util.List<Integer> getAllAlarmCodes() {
//        java.util.List<Integer> allCodes = new java.util.ArrayList<>();
//        if (batteryAlarmCodes != null) allCodes.addAll(batteryAlarmCodes);
//        if (motorAlarmCodes != null) allCodes.addAll(motorAlarmCodes);
//        if (engineAlarmCodes != null) allCodes.addAll(engineAlarmCodes);
//        if (otherAlarmCodes != null) allCodes.addAll(otherAlarmCodes);
//        return allCodes;
//    }
    
    /**
     * 检查是否包含指定的报警代码
     * @param alarmCode 要检查的报警代码
     * @return true: 包含该报警代码, false: 不包含
     */
//    public boolean containsAlarmCode(int alarmCode) {
//        return getAllAlarmCodes().contains(alarmCode);
//    }
    
    /**
     * 获取报警数据的完整状态描述
     * @return 包含等级、标志位和代码的状态描述
     */
    public String getAlarmStatusSummary() {
        StringBuilder summary = new StringBuilder();
        summary.append("报警等级: ").append(getMaxAlarmLevelDescription()).append("\n");
        summary.append("通用报警标志: ").append(getAlarmHexString()).append("\n");
        summary.append("电池报警数: ").append(getBatteryAlarmCount()).append("\n");
        summary.append("电机报警数: ").append(getMotorAlarmCount()).append("\n");
        summary.append("发动机报警数: ").append(getEngineAlarmCount()).append("\n");
        summary.append("其他报警数: ").append(getOtherAlarmCount()).append("\n");
        summary.append("总报警数: ").append(getTotalAlarmCodeCount());
        return summary.toString();
    }
}